package com.haois.ws.common.config.jackson;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

/**
 * @author 赖少涯
 * @version 1.0
 * @date 2018-02-08 14:01:07
 * @since 1.7
 */
@Configuration
public class JacksonConfig {

    private static final Map<Integer, DateTimeFormatter> DATE_TIME_FORMATTER_MAP;

    static {
        DATE_TIME_FORMATTER_MAP = new HashMap<>();
        DATE_TIME_FORMATTER_MAP.put(14, DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        DATE_TIME_FORMATTER_MAP.put(17, new DateTimeFormatterBuilder().appendPattern("yyyyMMddHHmmss").appendValue(ChronoField.MILLI_OF_SECOND, 3).toFormatter());
        DATE_TIME_FORMATTER_MAP.put(19, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        DATE_TIME_FORMATTER_MAP.put(23, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
    }

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        return baseObjectMapper();
    }

    @Bean
    public ObjectMapper objectMapperHasTypeInfo() {
        ObjectMapper objectMapper = baseObjectMapper();
        //序列化时写入类型信息,反序列化时则可不用指定类型
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        return objectMapper;
    }

    /**
     * 基础对象 jackson objectMapper
     */
    private ObjectMapper baseObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        //设置默认的时间格式、时区
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objectMapper.setDateFormat(sdf);
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));

        //允许单引号
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

        //属性名称允许不带双引号
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

        //忽略无法识别的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        //忽略transient标识的属性
        objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);

        // 忽略无法转换的对象 “No serializer found for class com.xxx.xxx”
        //objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);

        //格式化Temporal
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));

        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));

        javaTimeModule.addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
            @Override
            public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
                String text = StringUtils.trimToEmpty(jsonParser.getText());
                if ("".equals(text)) {
                    return null;
                }

                DateTimeFormatter dateTimeFormatter = DATE_TIME_FORMATTER_MAP.get(text.length());
                if (null == dateTimeFormatter) {
                    throw InvalidFormatException.from(jsonParser, String.format("Cannot deserialize value of type %s from String %s", LocalDateTime.class.getName(), text), text, LocalDateTime.class);
                }

                try {
                    return LocalDateTime.parse(text, dateTimeFormatter);
                } catch (DateTimeParseException e) {
                    throw InvalidFormatException.from(jsonParser, String.format("Cannot deserialize value of type %s from String %s", LocalDateTime.class.getName(), text), text, LocalDateTime.class);
                }
            }
        });

        objectMapper.registerModule(javaTimeModule);

        return objectMapper;
    }
}
